<template>
    <div class="chat-list">
        <div class="title">
            <div class="inner">
                <b>消息列表</b>
                <Checkbox v-model="is_unreply" @on-change="searchFriend">未回复</Checkbox>
            </div>
            <Input @on-enter="handlerSearch" v-model="searchKeyword" @on-change="changeSearchKey" placeholder="搜索" clearable>
                <Icon type="ios-search" slot="prefix"></Icon>
            </Input>
        </div>
        <div ref="scrollContent" class="content i-scrollbar">
            <!--搜索列表[作废]-->
            <template v-if="showSearchList">
<!--                <div v-for="(item, index) in searchChatConversation" @click="handleSelectConversation(item)" :key="index">-->
<!--                    <div class="chat-item" :class="{ 'active': currentFriend.friendid === item.friendid }">-->
<!--                        <Badge dot :count="0">-->
<!--                            <img class="avatar" v-if="item.avatar == ''" src="./../../../../assets/images/avater.png" alt />-->
<!--                            <img class="avatar" v-else v-lazy="item.avatar" alt />-->

<!--                        </Badge>-->
<!--                        <div class="info">-->
<!--                            <p class="name">{{ item.remark_name || item.nickname }}</p>-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->
                <div style="flex: 1; position: relative;">
                    <template v-for="(item, index) in searchChatConversation">
                        <!--分组名称-->
                        <div class="ivu-p-8" :key="item.value" :class="currentWechatGroupName === item.value ? 'active' : ''" @click="selectGroup(item)" >
                            <Row type="flex" align="middle" justify="space-between">
                                <Col>
                                    <strong>{{ item.value }}（{{item.total}}）</strong>
                                </Col>
                                <Col>
                                    <strong v-if="item.total > 0">
                                        <Icon type="ios-arrow-down" v-if="currentWechatGroupName === item.value"></Icon>
                                        <Icon type="ios-arrow-forward" v-else ></Icon>
                                    </strong>
                                </Col>
                            </Row>
                        </div>
                        <!--分组下好友列表-->
                        <simulationlist :key="index" :data="item" :name="currentWechatGroupName" :source="1" @clickwx="handleSelectConversation"></simulationlist>
                    </template>
                </div>
            </template>
            <!--好友分类列表-->
            <div v-else class="content-container no-right" style="display: flex; flex-direction: column;">
                <div style="flex: 1; position: relative;">
                    <template v-for="(item, index) in currentChatConversation">
                        <!--分组名称-->
                        <div class="ivu-p-8" :key="item.value" :class="currentWechatGroupName === item.value ? 'active' : ''" @click="selectGroup(item)" >
                            <Row type="flex" align="middle" justify="space-between">
                                <Col>
                                <strong>{{ item.value }}（{{item.total}}）</strong>
                            </Col>
                                <Col>
                                <strong v-if="item.total > 0">
                                    <Icon type="ios-arrow-down" v-if="currentWechatGroupName === item.value"></Icon>
                                    <Icon type="ios-arrow-forward" v-else ></Icon>
                                </strong>
                            </Col>
                            </Row>
                        </div>
                        <!--分组下好友列表-->
                        <simulationlist :ref="item.value" :key="index" :data="item" :name="currentWechatGroupName" :source="1" @clickwx="handleSelectConversation"></simulationlist>
                    </template>
                </div>
                <Spin fix v-if="conversionLoading"></Spin>
            </div>
        </div>
       
    </div>
</template>

<script>
// import dayjs from 'dayjs';
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex';
import { PatientList, WxFriend, RetrunVisit, SearchWechatFriendList } from '@/api/chat';
import simulationlist from '../../../robot/chatRecord/simulationlist';
export default {
    data() {
        return {
            searchKeyword: '',
            is_unreply: false,
            searchTimeoutObj: null,
            busy: false,
            showRight: true,
        };
    },
    components: {
        simulationlist,
    },
    watch: {
        searchKeyword(newVal) {
            if (newVal === '') {
                // this.setShowSearchList(false);
                // this.setSearchCoversation([]);
                this.searchFriend();
            }
        }
    },
    computed: {
        ...mapGetters('chatwebsocket/wechat', [
            'filterCurrentChatConversation'
        ]),
        ...mapState('chatwebsocket/wechat', [
            'currentFriend',
            'covPage',
            'currentConversationId',
            'currentWechat',
            'conversionLoading',
            'patientList',
            'currentChatConversation',
            'currentWechatGroupName',
            'searchChatConversation',
            'showSearchList',
            'searchKey',
        ]),
    },
    mounted() {
        this.searchKeyword = this.searchKey;
    },
    methods: {
        ...mapMutations('chatwebsocket/wechat', [
            'setcovItem',
            'covLimit',
            'setCurrentFriend',
            'setCovPage',
            'clearnChatMessages',
            'setReturnVisit',
            'setPatientList',
            'setWxFriendInfo',
            'setShowSearchList',
        ]),
        ...mapActions('chatwebsocket/wechat', [
            'setSearchCoversation',
            'setSearchKey',
            'webConversionReaded',
            'setCurrentWechatGroupName',
        ]),
        // 选择好友分组
        selectGroup(data) {
            if(parseInt(data.total) === 0) {
                return;
            }
            let name = this.currentWechatGroupName === data.value ? '' : data.value;
            // 清空分页
            if (this.currentWechatGroupName !== '') {
                this.$refs[this.currentWechatGroupName][0].initData();
            }
            this.setCurrentWechatGroupName(name);
        },
        // 选择好友
        handleSelectConversation(covItem) {
            this.setcovItem(covItem);
            this.setCovPage(1);
            this.clearnChatMessages();
            let cid = localStorage.getItem('currentProject');
            let wechatId = covItem.wechatid;
            let msg = {
                MsgType: 'queryHistoryMessage',
                Content: {
                    wechatid: wechatId,
                    friendid: covItem.friendid, // 好友id
                    cid, // 项目id
                    page: this.covPage, // 分页页数
                    pageSize: this.covLimit // 分页条数
                }
            };
            this.setCurrentFriend(covItem);
            // 发送已读给微博socket，标记已读
            this.$websocket.sendSock(msg);
            if (covItem.unread_cnt > 0) {
                /*let msgs = {
                    MsgType: 'TriggerMessageReadTask',
                    Content: {
                        WeChatId: wechatId,
                        FriendId: covItem.friendid // 好友id
                    }
                };
                this.$websocket.sendSock(msgs);*/
                this.webConversionReaded(covItem); // 标记为已读
            }
            // 获取好友信息
            this.getWxFriendInfo(covItem);
            // 获取患者列表
            this.getPatientList(covItem);
        },
        // 微信好友信息
        getWxFriendInfo(covItem) {
            WxFriend({
                wechatid: covItem.wechatid,
                friendid: covItem.friendid
            }).then(res => {
                this.setWxFriendInfo(res);
            });
        },
        // 患者列表
        getPatientList(covItem) {
            // console.log('covItem', covItem);
            this.setPatientList([]);
            PatientList({
                wechatid: covItem.wechatid,
                friendid: covItem.friendid,
                accountid: this.currentWechat.accountid
            }).then(res => {
                this.setPatientList(res.list);
                // 获取微聊回访记录
                this.getReturnVisit(covItem);
            });
        },
        // 回访记录
        getReturnVisit(covItem) {
            if (!this.patientList.length) return;
            RetrunVisit({
                patient_user_id: this.patientList[0].id,
                wechatid: covItem.wechatid,
                friendid: covItem.friendid
            }).then(res => {
                this.setReturnVisit(res.list);
            });
        },
        // 搜索通讯录
        handlerSearch() {
            if (!this.currentConversationId) {
                this.$Message.error('请要搜索的选择微信号');
                return;
            }

            this.searchFriend();
            // 搜索本地全局
            // this.setShowSearchList(true);
            // let searchConver = [];
            // this.currentChatConversation.forEach(item => {
            //     item.child.forEach(childItem => {
            //         if (childItem.friend_wechatno.indexOf(this.searchKey) === -1 && childItem.nickname.indexOf(this.searchKey) === -1 && childItem.remark_name.indexOf(this.searchKey) === -1) {
            //             return;
            //         }
            //         searchConver.push(childItem);
            //     })
            // })
            // this.setSearchCoversation(searchConver);

            // SearchWechatFriendList({
            //     wechat_id: this.currentConversationId,
            //     friend_no: this.searchKeyword,
            // }).then(res => {
            //     if (this.searchKeyword) {
            //         this.setShowSearchList(true);
            //         this.setSearchCoversation(res.list);
            //     }
            // });
        },
        // vuex记录搜索词
        changeSearchKey(e) {
            this.setSearchKey(this.searchKeyword);

            if (this.searchTimeoutObj) {
                clearTimeout(this.searchTimeoutObj);
            }
            // 存在关键词
            if (this.searchKeyword) {
                this.searchTimeoutObj = setTimeout(() => {
                    this.handlerSearch();
                }, 400);
            } else {
                this.setShowSearchList(false);
                this.setSearchCoversation([]);
            }
        },
        // 清空搜索词
        clearSearchKey() {
            this.searchKeyword = '';
        },
        searchFriend() {
            // 搜索
            this.$emit('searchFriend', {
                keywords: this.searchKeyword,
                is_unreply: this.is_unreply
            });
        },
    },
};
</script>

<style lang="less" scoped>

.chat-list {
    display: flex;
    flex-direction: column;
    height: 100%;
    // background-color: #e8e7e6;
    background: #f7f7f7;
    border-right: 1px solid rgb(214, 214, 214);

    .title {
        flex: 0 0 51px;
        line-height: 51px;
        padding: 0 16px;
        box-sizing: border-box;
        border-bottom: 1px solid #e8e7e6;
        // background: #f7f7f7;

        /deep/.ivu-input {
            background: #ebebeb;
            border: none;
        }
    }

    .content {
        flex: 1;
        overflow: auto;
        position: relative;
        overflow-x: hidden;
        overflow-y: auto;

        .chat-item {
            position: relative;
            display: flex;
            align-items: center;
            padding: 12px;
            height: 60px;
            box-sizing: border-box;
            cursor: pointer;
            background: #e8e7e6;

            .ivu-badge {
                height: 42px;
            }

            .avatar {
                height: 42px;
                width: 42px;
                border-radius: 3px;
            }

            .info {
                margin-left: 10px;

                .name {
                    min-height: 20px;
                    color: #333;
                    text-overflow: ellipsis;
                    overflow: hidden;
                    white-space: nowrap;
                    width: 140px;
                }

                .msg {
                    font-size: 12px;
                    width: 100%;
                    width: 180px;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    overflow: hidden;
                }
            }

            .time {
                position: absolute;
                right: 15px;
                top: 15px;
                font-size: 10px;
                color: #999;
            }

            .top-icon {
                position: absolute;
                right: 0;
                top: 0;
                height: 15px;
                width: 15px;
            }

            &:hover {
                background: rgb(222, 219, 219);
            }

            &.active {
                background: rgb(222, 219, 219);
            }
        }
    }
}

.chat-list .ivu-spin-fix {
    background: #e8e7e6;
}
.content-container{
    padding: 16px;
    height: 670px;
    overflow: auto;
}
.content-container .active {
    background: #e2e2e2;
}
.inner{
    margin-bottom: -10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.inner b{
    font-size: 16px;
}
</style>